/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* curA = l1;
        ListNode* curB = l2;
        ListNode* newHead = new ListNode;
        ListNode* cur = newHead;
        int flag = 0;
        while (curA && curB)
        {
            int sum = curA->val + curB->val + flag;           
            flag = sum / 10;
            ListNode* newNode = new ListNode(sum % 10, nullptr);
            
            cur->next = newNode;
            cur = cur->next;

            curA = curA->next;
            curB = curB->next;
        }

        while (curA)
        {
            int sum = curA->val + flag;           
            flag = sum / 10;
            ListNode* newNode = new ListNode(sum % 10, nullptr);
            cur->next = newNode;
            cur = cur->next;

            curA = curA->next;
        }
        while (curB)
        {
            int sum = curB->val + flag;           
            flag = sum / 10;
            ListNode* newNode = new ListNode(sum % 10, nullptr);
            cur->next = newNode;
            cur = cur->next;

            curB = curB->next;
        }
        if (flag)
        {
            ListNode* newNode = new ListNode(1, nullptr);
            cur->next = newNode;
        }

        ListNode* head = newHead->next;
        delete newHead;
        return head;
    }
};